package com.imclient.type;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @program: dj-liliping-edi-happigo
 * @description:
 * @author: Lillie
 * @create: 2018-10-16 15:06
 **/
public class OpenApiDemo {
    public static void main(String[] args) throws Exception {
        //
        System.out.println("时间戳： " + System.currentTimeMillis()/1000);
		/*String aa = java.net.URLEncoder.encode("ULf3DF2X77jgYe{jeRLzG=CATYvEDLh0");//moec1[pBRGH`FO=oy5{E+B1w2{4=EjiE","UTF-8
		System.out.println("返回内容： " + aa);
		System.out.println("还原内容： " + java.net.URLDecoder.decode(aa));
		if(1==1){
			return ;
		}*/
        //api_cust_no=7313450837&api_checkword=moec1%5BpBRGH%60FO%3Doy5%7BE%2BB1w2%7B4%3DEjiE

        /***********************1. 设置变量     ********************/
        String strUrlPre = "https://hope-test.happigo.com/openApi"; // 测试环境Url
        String strKey = "F30F52CC31C63347AF0C690386D22488"; // 签名密钥
        String strApplicationNO = "109000410001"; // 应用编号
        String strMethod = "HOPE000001"; // 方法编号
        StringBuffer sbRequestData = new StringBuffer(); // 请求内容 应用参数

        sbRequestData.append("<Program>");
        sbRequestData.append(" 	<parameters> ".trim()); // trim去掉空格
        sbRequestData.append(" 		<from_date>2018-10-16 00:00:00</from_date> ".trim());
        sbRequestData.append(" 		<to_date>2018-10-16 23:59:59</to_date> ".trim());
        sbRequestData.append(" 	</parameters> ".trim());
        sbRequestData.append(" 	<page> ".trim());
        sbRequestData.append(" 		<page_size>10</page_size> ".trim());
        sbRequestData.append(" 		<page_no>0</page_no> ".trim());
        sbRequestData.append(" 	</page> ".trim());
        sbRequestData.append(" </Program> ".trim());

		/*sbRequestData.append(" <Program> ".trim());
		sbRequestData.append(" 	<parameters> ".trim());
		sbRequestData.append(" 		<wh_code>101</wh_code> ".trim());
		sbRequestData.append(" 	</parameters> ".trim());
		sbRequestData.append(" 	<delyinfo> ".trim());
		sbRequestData.append(" 		<row1> ".trim());
		sbRequestData.append(" 			<wb_no>1102279378300</wb_no> ".trim());
		sbRequestData.append(" 			<order_no>20130217955938</order_no> ".trim());
		sbRequestData.append(" 			<receive_name>测试</receive_name> ".trim());
		sbRequestData.append(" 				<weight>1.0</weight> ".trim());
		sbRequestData.append(" 				<comments></comments> ".trim());
		sbRequestData.append(" 				<shipping_date>2013-02-22 08:16:40</shipping_date> ".trim());
		sbRequestData.append(" 				<tel></tel> ".trim());
		sbRequestData.append(" 				<mobile>123</mobile>				　　 ".trim());
		sbRequestData.append(" 				<pieces>1</pieces> ");
		sbRequestData.append(" 				<address>湖南省衡阳市石鼓区石鼓区(市区)石鼓市区)</address>				　　 ".trim());
		sbRequestData.append(" 				<request_time>0</request_time>				　　 ".trim());
		sbRequestData.append(" 				<receive_remark>1</receive_remark> ".trim());
		sbRequestData.append(" 		</row1>		　　 ".trim());
		sbRequestData.append(" 	</delyinfo> ".trim());
		sbRequestData.append(" </Program> ".trim());*/
        String strRequestData = sbRequestData.toString(); //.replaceAll(" ", "")
        //strRequestData = new String(strRequestData.getBytes(),"GBK");

        StringBuffer sbSystemArgs = new StringBuffer(); // 系统参数
        sbSystemArgs.append("app_id=" + strApplicationNO);
        sbSystemArgs.append("&charset=utf-8");
        sbSystemArgs.append("&data_type=xml");
        sbSystemArgs.append("&function_id=" + strMethod);
        sbSystemArgs.append("&sign_type=md5");
        sbSystemArgs.append("&time=" + System.currentTimeMillis()/1000);
        sbSystemArgs.append("&version=1.0");


        /***********************2. 生成签名数据     ********************/
        // 被加密内容： 系统参数 + 应用参数 + 签名密钥
        String strKeycontent = sbSystemArgs.toString()
                + strRequestData + strKey;
        // 进行MD5加密
        String strKeyMD5 = createMD5(strKeycontent);
        strKeyMD5 = strKeyMD5.toUpperCase();
        System.out.println("生成的MD5加密串： " + strKeyMD5);


        /***********************3. 设置签名证书     ********************/
        //签名证书生成的命令
        // keytool -import -alias happigo -keystore d:\hpg.jks -trustcacerts -file d:\hpg.cer
        System.setProperty("javax.net.ssl.trustStore", "D:\\hpg.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "111111");

        /***********************4. 发送请求，获取返回值     ********************/
        // 发送请求
        StringBuffer sbUrl = new StringBuffer(); // 请求URL内容
        sbUrl.append(strUrlPre);
        sbUrl.append("?");
        sbUrl.append(sbSystemArgs.toString());
        sbUrl.append("&sign=" + strKeyMD5);
        String strUrl = sbUrl.toString();
        System.out.println("请求内容： "  + strRequestData);
        String strResponse = doRequest(strUrl, strRequestData);
        System.out.println("返回内容： " + strResponse);
    }

    /**
     * MD5加密返回
     *
     * @param strText
     * @return
     */
    static public String createMD5(String strText) throws Exception {
        String password = strText;
        byte[] unencodedPassword = password.getBytes("UTF-8");

        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            return password;
        }
        md.reset();
        md.update(unencodedPassword);
        byte[] encodedPassword = md.digest();
        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        return buf.toString();
    }

    /**
     * Url请求处理
     *
     *
     * @param strUrl
     * @param sSendXml
     * @return
     * @throws Exception
     */
    static public String doRequest(String strUrl, String sSendXml)
            throws Exception {
        String value = "";
        OutputStream outputstream = null;
        InputStream ins = null;
        InputStreamReader inreder = null;
        BufferedReader in = null;
        try {
        	
        	/////////////////---------------------///////////////////////
        	
        	SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");//第一个参数为协议,第二个参数为提供者(可以缺省)
        	TrustManager[] tm = {new MyX509TrustManager()};
        	sslcontext.init(null, tm, new SecureRandom());
        	HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        		public boolean verify(String s, SSLSession sslsession) {
        			System.out.println("WARNING: Hostname is not matched for cert.");
        				return true;
        		}
        	};
        	HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
        	HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
        	////////////////////--------------------/////////////////////////////////////////
            URL url = new URL(strUrl);
            HttpURLConnection hcon = null;
            hcon = (HttpURLConnection) url.openConnection();
            hcon.setRequestProperty("Content-type", "text/html");
            hcon.setRequestProperty("Content-length", String.valueOf(-1));
            hcon.setRequestProperty("HTTP-Version","HTTP/1.0");
            //hcon.setRequestProperty("Charset", "UTF-8");
            hcon.setConnectTimeout(1000);
            hcon.setReadTimeout(6000);
            hcon.setUseCaches(false);
            hcon.setDefaultUseCaches(false);
            hcon.setDoOutput(true);

            hcon.setRequestMethod("POST");
            hcon.addRequestProperty("POST", "/  HTTP/1.1");
            outputstream = hcon.getOutputStream();
            outputstream.write(sSendXml.getBytes("UTF-8"));
            outputstream.flush();
            outputstream.close();

            ins = hcon.getInputStream();
            inreder = new InputStreamReader(ins,"UTF-8");

            in = new BufferedReader(inreder);
            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }

            inreder.close();
            ins.close();
            in.close();
            String text = buffer.toString();
            buffer = null;

            int code = hcon.getResponseCode();
            if (code == 200) {
                value = text;
                // System.out.println(value);
            } else {
                System.out.println("错误代码" + code);
            }
        } catch (Exception e) {
            throw new Exception("dealRequest,调用远程接口失败，接口不可达或中途出现异常，详细错误信息："
                    + e.getMessage(), e);
        } finally {
            try {
                if (outputstream != null) {
                    outputstream.close();
                }
                if (inreder != null) {
                    inreder.close();
                }
                if (ins != null) {
                    ins.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                throw new Exception("dealRequest,调用远程接口失败，资源释放异常，详细错误信息："
                        + e.getMessage(), e);
            }
        }

        return value;
    }
    
    

public static class MyX509TrustManager implements X509TrustManager{

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}
 
}



}

